﻿using CzJ_VoteSys.Common;
using CzJ_VoteSys.Models;
using CzJ_VoteSys.Models.Database;
using CzJ_VoteSys.Models.RequestModel;
using CzJ_VoteSys.Utils.Security;
using Microsoft.AspNetCore.Mvc;

namespace CzJ_VoteSys.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class UserController : Controller
    {
        private readonly CzJ_VoteSysContext _db;
        private readonly Services.IJWTService _jwtService;
        private readonly Services.UserService _userService;

        public UserController(CzJ_VoteSysContext db, Services.IJWTService jwtService, Services.UserService userService)
        {
            _db = db;
            _jwtService = jwtService;
            _userService = userService;
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ObjectResult Register([FromBody]Models.RequestModel.UserRegister model)
        {
            var user = _userService.GetUserByEmil(model.Email);

            if (user != null)
            {
                return ApiError.USER_ALREADY_EXIST;
            }

            var salt = MD5Helper.GenerateSalt();
            var hashPwd = MD5Helper.ComputeSaltedHash(model.Password, salt);

            var newUser = new User
            {
                Email = model.Email,
                UserPassword = hashPwd,
                Salt = salt
            };

            _db.Users.Add(newUser);
            var count = _db.SaveChanges();
            if (count == 0)
            {
                return ApiError.DB_NOT_CHANGE;
            }

            return Ok(null);
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ObjectResult Login([FromBody]Models.RequestModel.UserLogin model)
        {
            var user = _userService.GetUserByEmil(model.Email);

            if (user == null)
            {
                return ApiError.USER_NOT_FOUND;
            }

            var hashPwd = MD5Helper.ComputeSaltedHash(model.Password, user.Salt);

            if (hashPwd != user.UserPassword)
            {
                return ApiError.USER_PASSWORD_ERROR;
            }

            var token = _jwtService.CreateToken(user.UserId);

            return Ok(token);
        }

    }
}
